 ///
 /// @file    Singleton1.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-28 14:51:19
 ///
 
#include <iostream>
using std::cout;
using std::endl;

//需求：单例对象能自动回收
//解决方案二：atexit + destroy 


class Singleton
{
public:
	//在多线程环境下，是线程安全的吗？
	static Singleton * getInstance()
	{
		//加锁
		if(nullptr == _pInstance) {
			_pInstance = new Singleton();
			atexit(destroy);
		}
		return _pInstance;
	}

	//如果程序退出时，能自动调用destroy方法，也能解决该问题
	static void destroy()
	{
		if(_pInstance) {
			delete _pInstance;
			_pInstance = nullptr;
		}
	}

private:
	Singleton() {	cout << "Singleton()" << endl;	}
	~Singleton() {	cout << "~Singleton()" << endl;	}

private:
	static Singleton * _pInstance;
	int _data;
};

//在类之外进行初始化是一个特殊的时机
//Singleton * Singleton::_pInstance = nullptr;//饱汉(懒汉)模式 ==> 懒加载
//能够直接调用getInstance，是因为还是在类内部
Singleton * Singleton::_pInstance = getInstance();//饿汉模式

 
void test0() 
{
	//cout << Singleton::_pInstance << endl;//error
	Singleton * p1 = Singleton::getInstance();
	Singleton * p2 = Singleton::getInstance();
	cout << "p1:" << p1 << endl;
	cout << "p2:" << p2 << endl;
} 
 
int main(void)
{
	test0();
	return 0;
}
